package ru.jkff.jalgebra.core;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * User: jkff
 * Date: Aug 23, 2009
 * Time: 12:48:01 PM
 */
public abstract class CollectionFunctions {
    private CollectionFunctions() {}

    public static <T> PartialFunction<Collection<T>, T> getFirst() {
        return new PartialFunction<Collection<T>, T>() {
            public T apply(Collection<T> ts) throws IllegalArgumentException {
                if(ts.isEmpty())
                    throw new IllegalArgumentException("Empty collection");
                return ts.iterator().next();
            }
        };
    }

    public static <T> PartialFunction<List<T>, T> getElementAt(final int index) {
        return new PartialFunction<List<T>, T>() {
            public T apply(List<T> ts) throws IllegalArgumentException {
                if(index < 0 || index >= ts.size())
                    throw new IllegalArgumentException(
                            "Index "+index+" out of range for list of size "+ts.size());
                return ts.get(index);
            }
        };
    }

    public static <K,V> Function<Map<K,V>, V> getFromMap(final K key) {
        return new Function<Map<K, V>, V>() {
            public V apply(Map<K, V> map) {
                return map.get(key); 
            }
        };
    }
    
    public static <K,V> PartialFunction<Map<K,V>, V> getExistingFromMap(final K key) {
        return new Function<Map<K, V>, V>() {
            public V apply(Map<K, V> map) {
                if(!map.containsKey(key))
                    throw new IllegalArgumentException("Key " + key + " is not in the map");
                return map.get(key); 
            }
        };
    }
}
